
package com.weiqiao.mall.rest;

import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.aop.log.Log;
import com.weiqiao.mall.domain.AppUserEntity;
import com.weiqiao.mall.domain.EquityCardEntity;
import com.weiqiao.mall.domain.MemberShipEntity;
import com.weiqiao.mall.service.*;
import com.weiqiao.mall.service.dto.AppUserDTO;
import com.weiqiao.mall.service.vo.InviterVO;
import com.weiqiao.mall.service.vo.MemberConfigVO;
import com.weiqiao.mall.service.vo.RechargeBalanceVO;
import com.weiqiao.mall.util.ReturnMapUtil;
import com.weiqiao.modules.system.service.dto.UserQueryCriteria;
import com.weiqiao.utils.FileUtil;
import com.weiqiao.utils.PageUtil;
import com.weiqiao.utils.SecurityUtils;
import com.weiqiao.utils.StringUtils;
import org.apache.commons.collections.map.HashedMap;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 客户管理控制层
 *
 * @author PEI
 */
@RestController
@RequestMapping("/api")
public class CustomerController {

    // 客户管理控制层
    @Autowired
    private IAppUserService appUserService;

    // 权益卡，后期以调接口形式实现
    @Autowired
    private IEquityCardService equityCardService;

    // 会员设置
    @Autowired
    private IMemberConfigService memberConfigService;

    // 会员信息
    @Autowired
    private IMemberShipService memberShipService;

    // 会员信息
    @Autowired
    private ITeamService teamService;

    // 包含 推广员/普通用户
    @Log("客户列表")
    @GetMapping(value = "/customer-list")
    public ResponseEntity getCustomerList(HttpServletRequest request, Pageable pageable) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        Bson filter = this.getCustomerFilter(request);
        int total = appUserService.countNum(companyId, filter);
        List<AppUserDTO> list = appUserService.getAppUserPage(companyId, filter, pageable);
        return new ResponseEntity(PageUtil.toPage(list, total), HttpStatus.OK);
    }

    @Log("根据当前人id查询自己所有的上级信息")
    @GetMapping(value = "/up_uasrs/{recommend_id}")
    public ResponseEntity getUpUasrs(@PathVariable Integer recommend_id) {
        Integer company_id = SecurityUtils.getCompanyId();
        // 上级
        Map<String, Object> fatherMap = resultMap(recommend_id, company_id);
        Map<String, Object> grandpaMap = new HashedMap();
        // 上上级
        if (!fatherMap.isEmpty()) {
            Integer recommendId = Integer.parseInt(fatherMap.get("recommend_id").toString());
            grandpaMap = resultMap(recommendId, company_id);
        }
        Map<String, Object> resultMap = new HashedMap();
        resultMap.put("fatherMap", fatherMap);
        resultMap.put("grandpaMap", grandpaMap);
        return new ResponseEntity(resultMap, HttpStatus.OK);
    }

    private Map<String, Object> resultMap(Integer recommend_id, Integer company_id) {
        Map<String, Object> map = new HashedMap();
        AppUserEntity user = appUserService.getAppUserByFilter(new Document("user_id", recommend_id), company_id);
        if (user.getUser_id() > 0) {
            map.put("user_id", user.getUser_id());
            map.put("user_name", user.getUser_name());
            map.put("recommend_id", user.getRecommend_id());
            return map;
        }
        return map;
    }

    // 弹框用，查询指定的用户，且根据电话号查询后台的用户信息
    @GetMapping(value = "/customer-user-list")
    public ResponseEntity getCustomerAndUserList(HttpServletRequest request, Pageable pageable) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        Bson filter = this.getCustomerFilter(request);
        int total = appUserService.countNum(companyId, filter);
        List<AppUserEntity> list = appUserService.getCustomerUserPage(companyId, filter, pageable);
        return new ResponseEntity(PageUtil.toPage(list, total), HttpStatus.OK);
    }

    /**
     * 获取用户信息
     * 根据查询条件查询一条用户信息
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/get-customer")
    public ResponseEntity getCustomer(HttpServletRequest request) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        Bson filter = this.getCustomerFilter(request);
        AppUserEntity entity = appUserService.getAppUserByFilter(filter, companyId);
        return new ResponseEntity(entity, HttpStatus.OK);
    }    // 此处主要为客户列表提供，后期改为接口调用的形式

    /**
     * 通过电话号获取移动端用户
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/get-app-user-by-phone")
    public ResponseEntity getAppUserByPhone(HttpServletRequest request) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        String phoneList = request.getParameter("phone_list");
        System.out.println(phoneList);
        Bson filter = new Document("phone", new Document("$in", Arrays.asList(phoneList.split(","))));
        List<AppUserEntity> list = appUserService.getAppUserListByFilter(filter, companyId);
        return new ResponseEntity(list, HttpStatus.OK);
    }


    /**
     * 更新用户的用户等级
     *
     * @param entity
     * @return
     */
    @PostMapping(value = "/update-app-user-member-type")
    public ResponseEntity updateAppUserMemberType(@RequestBody @Validated AppUserEntity entity) {
        appUserService.updateUserMemberType(entity);
        return new ResponseEntity(true, HttpStatus.OK);
    }


    @Log("获取权益卡信息")
    @PostMapping(value = "/get-equity-card")
    public ResponseEntity getEquityCardList(HttpServletRequest request) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        // 获取权益卡
        Bson filter = Filters.and(Filters.eq("company_id", companyId), Filters.eq("delete_flag", 0),
                Filters.eq("state", 1));
        Bson sort = Filters.eq("create_time", -1);
        List<EquityCardEntity> equityList = equityCardService.findAllEquityCard(companyId, filter, sort);
        return new ResponseEntity(equityList, HttpStatus.OK);

    }

    @Log("批量修改客户类型")
    @PostMapping("/update-customer-type")
    public ResponseEntity updateCustomerType(HttpServletRequest request) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        String ids = request.getParameter("ids");
        String customerType = request.getParameter("customer_type");
        // 客户类型判断
        if (!StringUtil.isInteger(customerType)) {
            return new ResponseEntity(false, HttpStatus.OK);
        }
        // 需要修改的用户的id
        List<String> idList = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        if (!idList.isEmpty() && idList.size() > 0) {
            List<Integer> user_id_arr = new ArrayList<>();
            for (String id : idList) {
                if (StringUtil.isInteger(id)) {
                    user_id_arr.add(Integer.parseInt(id));
                }
            }
            Bson filter = Filters.in("user_id", user_id_arr);
            Document doc = new Document("customer_type", Integer.parseInt(customerType));
            appUserService.updateMany(doc, filter, companyId);
        }
        return new ResponseEntity(true, HttpStatus.OK);
    }

    @Log("修改会员类型")
    @PostMapping("/update-member-type")
    public ResponseEntity updateMemberType(HttpServletRequest request) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        String ids = request.getParameter("ids");
        String memberType = request.getParameter("member_type");
        // 会员类型判断
        if (!StringUtil.isInteger(memberType)) {
            return new ResponseEntity(false, HttpStatus.OK);
        }
        // 需要修改的用户的id
        List<String> idList = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        if (!idList.isEmpty() && idList.size() > 0) {
            // 当前不支持批量修改,故取列表第一个即可
            Integer user_id = Integer.parseInt(idList.get(0));
            /**
             * 获得当前被修改人的等级角色
             *      0: 客户 查看是否有会员消息，没有会员的话需要创建会员消息
             *      1：分销员 直接修改客户等级
             *      2：团长 && memberType == 3 修改角色等级的同时清空被修改人的团队id
             *      3：省长 不做考虑
             * 需要判断升级后的角色
             *      客户 ->  分销员，团长，省长  不做处理
             *      分销员 ->
             *               团长  下级客户全部升级为分销员，团队id不做修改
             *               省长  下级客户 不升级 团队id全部置空
             *      团长 ->  省长  下级客户 不升级 团队id全部置空
             */
            // 查询条件拼接
            Bson filter = Filters.in("user_id", user_id);
            Integer member_type = Integer.parseInt(memberType);
            // 修改内容拼接
            Document doc = new Document("member_type", member_type);
            // 获得用户信息
            AppUserEntity user = appUserService.getAppUserByFilter(filter, companyId);
            switch (user.getMember_type()) {
                case 0:
                    // 判断当前用户是否存在会员信息
                    if (user.getMember_id() == 0) {
                        // 创建会员信息
                        MemberShipEntity member = new MemberShipEntity();
                        member.setMember_id(user.getUser_id());
                        member.setName(user.getUser_name());
                        member.setPhone(user.getPhone());
                        member.setNickname(user.getNickname());
                        boolean bool = memberShipService.addMember(companyId, member);
                        if (bool) {
                            doc.append("member_id", user.getUser_id());
                        }
                    }
                    break;
                case 1:
                case 2:
                    upUserByRecommend(user, member_type);
                    break;
                case 3: // 当前用户是省长 -》 省长  清空团队id
                    appUserService.updateMany(
                            new Document("team_id", "")
                                    .append("team_name", ""),
                            new Document("user_id", user.getUser_id()),
                            companyId
                    );
                    break;
                default:
                    break;
            }
            appUserService.updateMany(doc, filter, companyId);
            return new ResponseEntity(true, HttpStatus.OK);
        }
        return new ResponseEntity(false, HttpStatus.OK);
    }

    /**
     * 修改用户角色是下级的连带修改
     * 只有用户当前等级是 分销员/团长 时调用该方法
     *
     * @param user        当前用户信息
     * @param member_type 修改后的等级信息
     */
    private void upUserByRecommend(AppUserEntity user, Integer member_type) {
        Integer company_id = user.getCompany_id();
        switch (member_type) {
            case 2: // 升级为团长，分销员：下级客户全部升级为分销员，团队id不做修改
                List<AppUserEntity> users = appUserService.getAppUserListByFilter(new Document("recommend_id", user.getUser_id()), company_id);
                List<Integer> ids = new ArrayList<>();
                users.forEach(entity -> ids.add(entity.getUser_id()));
                appUserService.updateMany(new Document("member_type", 1), new Document("user_id", new Document("$in", ids)), company_id);
                break;
            case 3: // 升级为省长 下级客户 不升级 团队id全部置空
                appUserService.updateMany(
                        new Document("team_id", "")
                                .append("team_name", ""),
                        new Document("team_id", user.getTeam_id()),
                        company_id
                );
                break;
        }
    }

    @Log("批量修改会员直播权限 1：开启 / 0：关闭")
    @PostMapping("/update-live-config")
    public ResponseEntity updateLiveConfig(HttpServletRequest request) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        String ids = request.getParameter("ids");
        String liveConfig = request.getParameter("live_config");
        // 直播权限判断
        if (!StringUtil.isInteger(liveConfig)) {
            return new ResponseEntity(false, HttpStatus.OK);
        }
        // 需要修改的用户的id
        List<String> idList = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        if (!idList.isEmpty() && idList.size() > 0) {
            List<Integer> user_id_arr = new ArrayList<>();
            for (String id : idList) {
                if (StringUtil.isInteger(id)) {
                    user_id_arr.add(Integer.parseInt(id));
                }
            }
            Bson filter = Filters.in("user_id", user_id_arr);
            Document doc = new Document("live_authority", Integer.parseInt(liveConfig));
            appUserService.updateMany(doc, filter, companyId);
        }
        return new ResponseEntity(true, HttpStatus.OK);
    }

    @Log("更新客户等级")
    @PostMapping("/update-customer-grade")
    public ResponseEntity updateCustomerGrade(HttpServletRequest request) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        String ids = request.getParameter("ids");
        String gradeId = request.getParameter("grade_id");
        // 客户等级判断
        if (StringUtil.isBlank(gradeId)) {
            return new ResponseEntity(false, HttpStatus.OK);
        }
        // 空转换
        if ("0".equals(gradeId) || "null".equals(gradeId)) {
            gradeId = "";
        }
        // 需要修改的用户的id
        List<String> idList = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        if (!idList.isEmpty() && idList.size() > 0) {
            List<Integer> user_id_arr = new ArrayList<>();
            for (String id : idList) {
                if (StringUtil.isInteger(id)) {
                    user_id_arr.add(Integer.parseInt(id));
                }
            }
            Bson filter = Filters.in("user_id", user_id_arr);
            Document doc = new Document("grade_id", gradeId);
            appUserService.updateMany(doc, filter, companyId);
        }
        return new ResponseEntity(true, HttpStatus.OK);
    }

    @Log("加标签")
    @PostMapping("/update-tags")
    public ResponseEntity updateTags(HttpServletRequest request) {
        return new ResponseEntity(true, HttpStatus.OK);
    }

    @Log("批量设置权益卡")
    @PostMapping("/update-equity-card")
    public ResponseEntity updateEquityCard(HttpServletRequest request) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        String ids = request.getParameter("ids");
        String equityId = request.getParameter("equity_id");
        // 权益卡判断
        if (!StringUtil.isLong(equityId)) {
            return new ResponseEntity(false, HttpStatus.OK);
        }
        // 需要修改的用户的id
        List<String> idList = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        if (!idList.isEmpty() && idList.size() > 0) {
            List<Integer> userIdList = new ArrayList<>();
            for (String id : idList) {
                if (StringUtil.isInteger(id)) {
                    userIdList.add(Integer.parseInt(id));
                }
            }
            Bson filter = Filters.in("user_id", userIdList);
            // 权益卡为0，代表置空权益卡
            Document doc = new Document("equity_id", Long.parseLong(equityId) == 0 ? "" : equityId);
            appUserService.updateMany(doc, filter, companyId);
        }
        return new ResponseEntity(true, HttpStatus.OK);
    }

    // 客户列表查询条件
    private Bson getCustomerFilter(HttpServletRequest request) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        Document doc = new Document();
        // 页面类型 0：推广员列表   1：普通用户列表
        String type = request.getParameter("type");
        // 关键词
        String key_word = request.getParameter("key_word");
        // 团队
        String key_word_team = request.getParameter("key_word_team");
        String key_word_inviter = request.getParameter("key_word_inviter");
        // 创建时间
        String create_time = request.getParameter("last_buy_time");
        // 会员类型
        String member_type = request.getParameter("member_type");
        // 根据手机号进行查询
        String phone = request.getParameter("phone");

        // 根据手机号/微信昵称/用户姓名/用户id 模糊查询
        if (!StringUtil.isBlank(key_word)) {
            Pattern pattern = Pattern.compile("^.*" + key_word + ".*$", Pattern.CASE_INSENSITIVE);
            List<Document> docList = new ArrayList<>();
            // 手机号
            if (StringUtil.isLong(key_word)) {
                docList.add(new Document("phone", pattern));
            }
            // 微信昵称
            docList.add(new Document("nickname", pattern));
            // 用户id
            if (StringUtil.isInteger(key_word)) {
                Integer user_id = Integer.parseInt(key_word);
                docList.add(new Document("user_id", user_id));
            }
            // 用户姓名
            docList.add(new Document("user_name", pattern));
            doc.append("$or", docList);
        }
        // 团队
        if (!StringUtils.isBlank(key_word_team)) {
            if (StringUtils.isInteger(key_word_team)) {
                // 团队id
                doc.append("team_id", Integer.parseInt(key_word_team));
            } else {
                // 团队名称
                doc.append("team_name", new Document("$regex", key_word_team));
            }
        }
        // 邀请人
        if (!StringUtils.isBlank(key_word_inviter)) {
            if (StringUtils.isInteger(key_word_inviter)) {
                // 根据邀请人编号搜索
                doc.append("recommend_id", Integer.parseInt(key_word_inviter));
            } else {
                // 根据邀请人昵称搜索，首先根据昵称查编号，然后邀请人编号在区间范围内
                Pattern pattern = Pattern.compile("^.*" + key_word_inviter + ".*$", Pattern.CASE_INSENSITIVE);
                List<Integer> list = appUserService.getAppUserIdList(Filters.eq("nickname", pattern), companyId);
                doc.append("recommend_id", new Document("$in", list));
            }
        }
        // 创建时间
        if (!StringUtil.isBlank(create_time) && create_time.split("~").length > 1) {
            try {
                String start = create_time.split("~")[0];
                String end = create_time.split("~")[1];
                Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(start);
                Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(end);
                doc.append("create_time", new Document("$gt", String.valueOf(startDate.getTime())).append("$lt",
                        String.valueOf(endDate.getTime())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        // 页面类型 0：推广员列表   1：普通用户列表
        if (!StringUtil.isBlank(type) && StringUtil.isInteger(type)) {

            int memberType = Integer.parseInt(type);
            if (memberType != 0) {
                // 邀请人为当前id的客户信息
                doc.append("member_type", 0);
            } else {
                doc.append("member_type", new Document("$in", Arrays.asList(1, 2, 3)));
            }
            // 获得权限设置
            setAuthority(request, doc, memberType);
        }
        // 等级角色
        if (!StringUtil.isBlank(member_type) && StringUtil.isInteger(member_type)) {
            doc.append("member_type", Integer.parseInt(member_type));
        }

        // 电话号查询
        if (!StringUtil.isBlank(phone)) {
            doc.append("phone", phone);
        }

        return doc;
    }

    private void setAuthority(HttpServletRequest request, Document doc, int memberType) {
        int company_id = Integer.parseInt(request.getParameter("company_id"));

        /**
         * 以下字段用来区分列表显示内容
         * 1、user_id：当用户id为空时说明当前登录用户是管理员，不做限制
         * 2、如果user_id不为空，则根据member_type来区别显示内容
         * 3、如果member_type = 3（省长） 查询中间表获得团队信息查询用户列表
         * 4、如果member_type = 2（团长） 根据team_id查询团队成员
         */
        String user_user_id = request.getParameter("user_user_id");
        String user_member_type = request.getParameter("user_member_type");
        String user_team_id = request.getParameter("user_team_id");

        if (!StringUtil.isInteger(user_user_id) &&
                StringUtil.isBlank(user_member_type) &&
                StringUtil.isBlank(user_team_id)
        ) {
            return;
        }
        Integer user_id = Integer.parseInt(user_user_id);

        if (memberType == 1) { // 客户列表
            // 邀请人为当前id的客户信息
            doc.append("recommend_id", user_id);
        }
        switch (user_member_type) {
            case "3": // 省长
                // 查询团队表，获得该团长创建的团队信息
                List<String> dto = teamService.teamList(company_id, new Document("create_id", user_id));
                doc.append("$or", Arrays.asList(
                        new Document("team_id", new Document("$in", dto)), // 团成员
                        new Document("recommend_id", user_id)) // 邀请人为当前id的客户信息
                );
                break;
            case "2": // 团长
                doc.append("team_id", user_team_id);
                break;
            default:
                break;
        }
    }

    @Log("导出客户列表表格")
    @PostMapping(value = "/export-customer-excel")
    public void exportCustomerExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        Bson filter = this.getCustomerFilter(request);
        // 页面类型 0：推广员列表   1：普通用户列表
        String type = request.getParameter("type");
        // 表格内容拼装
        List<Map<String, Object>> list = appUserService.exportWorkersInfo(companyId, type, filter);
        FileUtil.downloadExcel(list, response);
    }

    @Log("员工列表")
    @GetMapping(value = "/workers-list")
    public ResponseEntity getWorkersList(HttpServletRequest request, Pageable pageable) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        Bson filter = this.getWorkersFilter(request);
        int total = appUserService.countNum(companyId, filter);
        List<AppUserDTO> list = appUserService.getAppUserPage(companyId, filter, pageable);
        return new ResponseEntity(PageUtil.toPage(list, total), HttpStatus.OK);
    }

    // 员工列表查询条件
    private Bson getWorkersFilter(HttpServletRequest request) {
        String keyword = request.getParameter("keyword");// 关键词，手机号，微信昵称，客户编号
        String is_bind = request.getParameter("is_bind");
        String custom_name = request.getParameter("custom_name");
        String sys_group_name = request.getParameter("sys_group_name");
        // 权益卡
        String equity = request.getParameter("equity");
        // 客户类型为1的是员工
        Document doc = new Document("customer_type", 1);
        if (!StringUtil.isBlank(keyword)) {
            Integer user_id = StringUtil.isInteger(keyword) ? Integer.parseInt(keyword) : 0;
            Pattern pattern = Pattern.compile("^.*" + keyword + ".*$", Pattern.CASE_INSENSITIVE);
            List<Document> docList = new ArrayList<>();
            docList.add(new Document("phone", pattern));
            docList.add(new Document("nickname", pattern));
            docList.add(new Document("user_id", user_id));
            doc.append("$or", docList);
        }
        if (StringUtil.isInteger(is_bind)) {
            // 通过判断此字段是否存在，来确定是否绑定银行卡
            doc.append("bankCardInfo", new Document("$exists", Integer.parseInt(is_bind) == 1 ? true : false));
        }
        if (!StringUtils.isBlank(custom_name)) {
            Pattern pattern = Pattern.compile("^.*" + custom_name + ".*$", Pattern.CASE_INSENSITIVE);
            doc.append("custom_name", pattern);
        }
        if (!StringUtils.isBlank(sys_group_name)) {
            Pattern pattern = Pattern.compile("^.*" + sys_group_name + ".*$", Pattern.CASE_INSENSITIVE);
            doc.append("sys_group_name", pattern);
        }
        if (!StringUtils.isBlank(equity)) {
            doc.append("equity_id", equity);
        }
        return doc;
    }

    @Log("员工绑定卡片信息")
    @PostMapping(value = "/binding-card")
    public ResponseEntity bindingCard(HttpServletRequest request) {
        int company_id = Integer.parseInt(request.getParameter("company_id"));
        String ids = request.getParameter("user_ids");
        String owner_name = request.getParameter("owner_name");
        String card_id = request.getParameter("card_id");
        String bank_type = request.getParameter("bank_type");
        String bank_name = request.getParameter("bank_name");
        Document doc = new Document();
        if (StringUtil.isLong(card_id)) {
            doc.append("bankCardInfo.card_id", card_id);
        }
        if (!StringUtils.isBlank(bank_name)) {
            doc.append("bankCardInfo.bank_name", bank_name);
        }
        if (!StringUtils.isBlank(bank_type)) {
            doc.append("bankCardInfo.bank_type", bank_type);
        }
        if (!StringUtils.isBlank(owner_name)) {
            doc.append("bankCardInfo.owner_name", owner_name);
        }
        if (doc.size() > 0) {
            doc.append("binding_type", 1);
        }
        // 需要绑卡的用户的
        List<String> idList = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        if (!idList.isEmpty() && idList.size() > 0) {
            List<Integer> user_id_arr = new ArrayList<>();
            for (String id : idList) {
                if (StringUtil.isInteger(id)) {
                    user_id_arr.add(Integer.parseInt(id));
                }
            }
            if (user_id_arr != null && user_id_arr.size() > 0) {
                Bson filter = Filters.eq("company_id", company_id);
                filter = Filters.and(filter, Filters.in("user_id", user_id_arr));
                appUserService.updateMany(doc, filter, company_id);
            }

        }
        return new ResponseEntity(true, HttpStatus.OK);
    }

    @Log("导出职工表格")
    @PostMapping(value = "/export-workers-excel")
    public void exportWorkersExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        Bson filter = this.getWorkersFilter(request);
        // 表格内容拼装
        List<Map<String, Object>> list = appUserService.exportWorkersInfo(companyId, "", filter);
        FileUtil.downloadExcel(list, response);
    }

    @Log("获取会员设置信息")
    @GetMapping(value = "/get-Member-config")
    public ResponseEntity getMemberConfig(@RequestParam("company_id") Integer companyId) {
        return memberConfigService.getCompanyMemberConfig(companyId);
    }

    @Log("更新会员设置信息")
    @PostMapping(value = "/update-member-config")
    public ResponseEntity updateMemberConfig(@Validated @RequestBody MemberConfigVO entity) {
        return new ResponseEntity(memberConfigService.updateCompanyMemberConfig(entity), HttpStatus.OK);
    }

    @Log("编辑用户余额信息")
    @PutMapping("/edit-recharge-balance")
    public ResponseEntity editRechargeBalance(@Validated @RequestBody RechargeBalanceVO entity) {
        return new ResponseEntity(appUserService.editRechargeBanlance(entity), HttpStatus.OK);
    }

    @Log("分页获取业务员信息")
    @PostMapping("/get-clerk-list")
    public ResponseEntity getClerkList(@RequestParam("company_id") Integer companyId,
                                       @RequestParam("blurry") String blurry, Pageable pageable) {
        UserQueryCriteria criteria = new UserQueryCriteria();
        criteria.setCompanyId(companyId);
        criteria.setBlurry(blurry);
        return new ResponseEntity(appUserService.getClerkAndPage(criteria, pageable), HttpStatus.OK);
    }

    @Log("绑定邀请人ID、业务员信息")
    @PostMapping("/update-inviter-id")
    public ResponseEntity updateInviterId(InviterVO entity) {
        int type = entity.getType();
        if (type == 1) {
            // 修改邀请人id
            return new ResponseEntity(appUserService.updateUserInviter(entity), HttpStatus.OK);
        } else if (type == 2) {
            return new ResponseEntity(appUserService.updateUserTeam(entity), HttpStatus.OK);
        } else {
            return new ResponseEntity(
                    ReturnMapUtil.returnMap(false, "参数错误！type不能为空。"),
                    HttpStatus.OK);
        }
    }

}
